<?php

namespace App\Services\Base;
use App\Common\Constant;
use App\Models\Base\FileGroup;
use App\Models\Base\Files;
use App\Repository\SystemConfigRepository;
use App\Services\BaseService;

/**
 * 文件存储相关业务类
 *
 * @package App\Http\Services
 * @author WangBin
 * @date 2021-06-11
 */
class FileService extends BaseService
{
    /**
     * 保存文件信息
     *
     * @param array $data
     * @return
     */
    public function save(array $data)
    {
        $result = ['file_url' => '', 'file_id' => 0];
        $baseUrl = SystemConfigRepository::getInstance()->get(Constant::KV_KEY_BASE_URL);
        $file = Files::saveData($data);
        if($file->file_id) {
            $result['file_id'] = $file->file_id;
            $result['file_url'] = $baseUrl . $file->relative_path . $file->storage_name;
        }
        return $result;
    }

    /**
     * 文件分组列表
     *
     * @return
     */
    public function getGroupList()
    {
        $result = ['total' => 0, 'list' => []];
        $groups = FileGroup::getList();
        $result['total'] = $groups->count();
        $result['list'] = $groups;
        return $result;
    }

    /**
     * 获取文件列表
     *
     * @param array $filter
     * @return array $result
     */
    public function getList(array $filter = [])
    {
        $result = ['total' => 0, 'list' => []];
        // 获取服务地址
        $baseUrl = KvService::getInstance()->get(Constant::KV_KEY_BASE_URL);
        $files = Files::getByFilter($filter);
        $result['total'] = $files->count();
        $files = $files->offset($filter['page'] * $filter['limit'])->limit($filter['limit'])->get();
        $result['list'] = $files->each(function ($item) use ($baseUrl) {
            $item->file_url = $baseUrl . $item->relative_path . $item->storage_name;
        });
        $result['list'] = $files;
        return $result;
    }
}
